/**
 * APP端原生视图推送通知实现
 */
export class appPush {
	constructor(option = {}) {
		// --- 属性初始化 ---
		this.inApp = option.inApp; // APP内横幅提醒
		this.voice = option.voice; // 声音提醒
		this.vibration = option.vibration; // 振动提醒
		this.messageType = option.messageType || ''; // 消息分类
		this.userId = option.userId; // 用户ID
		this.nickName = option.nickName; // 用户昵称
		this.messageTitle = option.messageTitle || '新消息';
		this.messageTime = option.messageTime || '现在';
		this.messageContent = option.messageContent || '您有一条新消息，请注意查收。';
		this.messageImage = option.messageImage || ''; // 默认为空

		// --- 尺寸计算 ---
		this.system = uni.getSystemInfoSync();
		this.screenWidth = this.system.screenWidth;
		this.propotation = this.screenWidth / 750; // rpx to px 比例

		this.popupViewWidth = this.propotation * 710;
		this.popupViewHeight = this.propotation * 140;
		this.viewContentPadding = this.propotation * 20;

		// --- 动画与时间 ---
		this.duration = 200; // 动画持续时间
		this.closeTime = 3500; // 自动关闭延时

		// --- 状态与实例 ---
		this.top = (this.propotation * 20) + this.system.statusBarHeight;
		this.body = null; // 原生视图实例
		this.isDragging = false; // 拖动状态
		this.initialTouch = { pageX: 0, pageY: 0 }; // 初始触摸点
	}

	/**
	 * 创建并绘制原生推送视图
	 */
	createView() {
		this.body = new plus.nativeObj.View('appPushPopupView', {
			top: `${this.top}px`,
			left: `${this.propotation * 20}px`,
			height: `${this.popupViewHeight}px`,
			width: `${this.popupViewWidth}px`
		});

		// 绘制背景
		this.body.drawRect({
			color: "rgba(255, 255, 255, 0.95)",
			radius: "12px"
		}, {
			shadow: "0px 4px 12px rgba(0,0,0,0.1)"
		});

		// 绘制内容
		const viewContentList = [
			// 头像
			{
				tag: 'img',
				id: 'avatar',
				src: this.messageImage,
				position: {
					top: `${this.viewContentPadding}px`,
					left: `${this.viewContentPadding}px`,
					width: `${this.propotation * 100}px`,
					height: `${this.propotation * 100}px`,
					// a-circle: true, // plus.nativeObj.View 不支持圆角图片，需预处理或用遮罩
				}
			},
			// 标题
			{
				tag: 'font',
				id: 'push-title',
				text: this.messageTitle,
				textStyles: {
					size: `${this.propotation * 30}px`,
					color: "#202123",
					weight: "bold",
					overflow: "ellipsis",
					whiteSpace: "nowrap"
				},
				position: {
					top: `${this.viewContentPadding + this.propotation * 5}px`,
					left: `${this.propotation * 140}px`,
					width: `${this.popupViewWidth - this.propotation * 260}px`,
					height: `${this.propotation * 40}px`,
				}
			},
			// 内容
			{
				tag: 'font',
				id: 'push-content',
				text: this.messageContent,
				textStyles: {
					size: `${this.propotation * 26}px`,
					color: "#4F555B",
					overflow: "ellipsis",
					whiteSpace: "nowrap"
				},
				position: {
					top: `${this.propotation * 80}px`,
					left: `${this.propotation * 140}px`,
					width: `${this.popupViewWidth - this.propotation * 260}px`,
					height: `${this.propotation * 35}px`,
				}
			},
			// "查看" 按钮
			{
				tag: 'img',
				id: 'view-btn',
				src: '/static/ck.png', // 使用图片代替文字按钮，样式更可控
				position: {
					top: `${(this.popupViewHeight - this.propotation * 55) / 2}px`, // 垂直居中
					right: `${this.viewContentPadding}px`,
					width: `${this.propotation * 100}px`,
					height: `${this.propotation * 55}px`,
				}
			},
		];
		this.body.draw(viewContentList);
		this.addEventListeners();
	}

	/**
	 * 为原生视图添加事件监听器
	 */
	addEventListeners() {
		this.body.addEventListener("click", (e) => {
			if (!this.isDragging) {
				this.navigateToTarget();
				this.hide();
			}
		});

		this.body.addEventListener("touchstart", (e) => {
			this.isDragging = false;
			this.initialTouch.pageX = e.pageX;
			this.initialTouch.pageY = e.pageY;
		});

		this.body.addEventListener("touchmove", (e) => {
			const deltaY = e.pageY - this.initialTouch.pageY;
			if (Math.abs(deltaY) > 5) {
				this.isDragging = true; // 标记为拖动
				if (deltaY < 0) { // 向上滑动
					this.body.setStyle({ top: `${this.top + deltaY}px` });
				}
			}
		});

		this.body.addEventListener("touchend", (e) => {
			const deltaY = e.pageY - this.initialTouch.pageY;
			// 如果是向上拖动超过一定阈值，则关闭
			if (this.isDragging && deltaY < -20) {
				this.hide();
			} else {
				// 否则，弹回原位
				this.body.setStyle({ top: `${this.top}px`, transition: { duration: 150 } });
			}
			// 重置拖动状态
			setTimeout(() => this.isDragging = false, 50);
		});
	}

	/**
	 * 根据消息类型跳转到相应页面
	 */
	navigateToTarget() {
		console.warn("准备打开通知窗口:", this.messageType);
		if (this.messageType === 'OPEN_CHAT' && this.userId) {
			const params = {
				userId: this.userId,
				nickName: this.nickName,
				avatar: this.messageImage,
				group: false // 假设都是单聊
			};
			uni.navigateTo({
				url: `/pages_sub/user/chat/chat?user=${JSON.stringify(params)}`,
				fail: (err) => console.error(`[AppPush] 打开聊天窗口失败: ${err.errMsg}`)
			});
		} else if (this.messageType === "REPLY_COMMENT") {
			uni.reLaunch({
				url: `/pages/tabBar/time-axis/time-axis`,
				fail: (err) => console.error(`[AppPush] 打开时光轴失败: ${err.errMsg}`)
			});
		} else {
			// 对于其他未知类型，可以不跳转或给一个通用提示
			console.log("[AppPush] 未知的通知类型，不执行跳转。");
		}
	}

	/**
	 * 显示推送通知
	 */
	show() {
		this.playTips();
		if (!this.inApp) {
			return;
		}

		// 确保同一时间只有一个推送视图
		const existingView = plus.nativeObj.View.getViewById('appPushPopupView');
		if (existingView) {
			existingView.close();
		}

		this.createView();

		this.body.show();
		this.animateIn();

		// 设置自动关闭
		setTimeout(() => {
			if (this.body) {
				this.hide();
			}
		}, this.closeTime);
	}

	/**
	 * 隐藏推送通知
	 */
	hide() {
		if (!this.body) return;

		this.animateOut(() => {
			if (this.body) {
				this.body.close();
				this.body = null;
			}
		});
	}

	/**
	 * 动画：进入
	 */
	animateIn() {
		const options = { type: 'slide-in-top', duration: this.duration };
		plus.nativeObj.View.startAnimation(options, this.body);
	}

	/**
	 * 动画：退出
	 * @param {Function} callback - 动画完成后的回调
	 */
	animateOut(callback) {
		const options = { type: 'slide-out-top', duration: this.duration };
		plus.nativeObj.View.startAnimation(options, this.body, callback);
	}

	/**
	 * 播放提示音和振动
	 */
	playTips() {
		if (this.voice) {
			const platform = uni.getSystemInfoSync().platform;
			if (platform === 'ios') {
				const player = plus.audio.createPlayer("/static/audio/ios.mp3");
				player.play();
			} else if (platform === 'android') {
				const main = plus.android.runtimeMainActivity();
				const RingtoneManager = plus.android.importClass("android.media.RingtoneManager");
				const uri = RingtoneManager.getActualDefaultRingtoneUri(main, RingtoneManager.TYPE_NOTIFICATION);
				if (uri) {
					const MediaPlayer = plus.android.importClass("android.media.MediaPlayer");
					const player = MediaPlayer.create(main, uri);
					player.setLooping(false);
					player.prepare();
					player.start();
				}
			}
		}
		if (this.vibration) {
			plus.device.vibrate();
		}
	}
}

export default appPush;